﻿using System;
using TouchSocket.Core;
using TouchSocket.Http;
using TouchSocket.Sockets;

namespace configstore.CSM.Host
{
    using configstore.CSM.plugins;
    using ExcelConfig;
    public class WebHost : IWebHost
    {
        internal HttpService? httpService { get; set; }
        public WebHost()
        {
            httpService = new HttpService();
        }
        public ServerState State { get { return httpService?.ServerState ?? ServerState.Stopped; } }
        public async Task Start()
        {
            var allow_cors = AppConfig.ReadGobalValue<string>("跨域请求") == "支持";
            var uris = AppConfig.Array("监听地址");
            var _iphosts = new Queue<IPHost>();
            foreach (var uri in uris)
            {
                if (AppConfig.YesOrNo("本地回环"))
                {
                    _iphosts.Enqueue(new IPHost($"127.{uri}"));
                    Console.WriteLine($"注册地址' 127.{uri}");
                }
                else
                {
                    _iphosts.Enqueue(new IPHost(uri));
                    Console.WriteLine($"注册地址' {uri}");
                }
            }

            try
            {
                httpService = new HttpService();
                await httpService.SetupAsync(new TouchSocketConfig()//加载配置
                     .SetListenIPHosts(_iphosts.ToArray())
                     .SetServerName("config-store#1.0.0")
                     .ConfigureContainer(a =>
                     {
                         //a.AddConsoleLogger();
                         if (allow_cors)
                         {
                             //添加跨域服务
                             a.AddCors(corsOption =>
                             {
                                 //添加跨域策略，后续使用policyName即可应用跨域策略。
                                 corsOption.Add(AppConfig.Text("跨域名称"), corsBuilder =>
                                 {
                                     corsBuilder.AllowAnyMethod()
                                         .WithOrigin(AppConfig.Text("跨域目标")).WithHeaders("content-type");
                                 });
                             });
                         }
                     })
                     .ConfigurePlugins(a =>
                     {
                         if (allow_cors) a.UseCors(AppConfig.Text("跨域名称"));

                         a.Add<TestPlug>();
                         a.Add<AppPlug>();

                         a.UseDefaultHttpServicePlugin();
                     }));

                await httpService.StartAsync();
            }catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
            Console.WriteLine("配置存储中心: 已启动");
        }

        public async Task Stop()
        {
            if (httpService == null) return;
            await httpService.StopAsync();
            Console.WriteLine("配置存储中心: 已停止");
        }

        public void Dispose()
        {
            if (this.httpService != null)
            {
                this.httpService.Dispose();
                this.httpService = null;
            }
        }
    }
}
